/*
 * @Author: Wangjun
 * @Date: 2021-09-27 21:18:15
 * @LastEditTime: 2021-09-27 21:28:15
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \godriver\sqlite3\test\main.go
 * hnxr
 */
package main

import (
	"fmt"
	"time"

	"gitee.com/haodreams/godriver/sqlite3"
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	Code  string
	Price int
}

func main() {
	db, err := gorm.Open(sqlite3.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 迁移 schema
	db.AutoMigrate(&Product{})

	num := 10000
	now := time.Now()
	var product Product

	err = db.Transaction(func(tx *gorm.DB) error {
		for i := 0; i < num; i++ {
			product.ID = uint(i + 1)
			product.Price = 100 + i
			tx.Create(&product)
		}
		return nil
	})

	fmt.Println(time.Since(now), err)

	// Create
	// db.Create(&Product{Code: "D42", Price: 100})

	// // Read
	// db.First(&product, 1)                 // 根据整形主键查找
	// db.First(&product, "code = ?", "D42") // 查找 code 字段值为 D42 的记录

	// // Update - 将 product 的 price 更新为 200
	// db.Model(&product).Update("Price", 200)
	// // Update - 更新多个字段
	// db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段
	// db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

	// // Delete - 删除 product
	// db.Delete(&product, 1)
}
